﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ReaderB;

namespace RFID信息初始化工作台
{
    public class FK
    {
        private byte fComAdr = 0xff; //当前操作的ComAdr
        private byte fBaud;
        private int frmcomportindex;
        private int openresult;

        private int fOpenComIndex; //打开的串口索引号

        public bool Connection(int type)
        {
            try
            {

                fComAdr = 0;
                fBaud = 5;

                int port = 3;
                if (type != 1)
                    port = 7;
                fComAdr = Convert.ToByte("FF", 16); // $FF;
               /// fComAdr = Convert.ToByte()
                fBaud = Convert.ToByte(3);
                if (fBaud > 2)
                    fBaud = Convert.ToByte(fBaud + 2);
                if (type == 1)
                    frmcomportindex = 3;
                else
                    frmcomportindex = 7;
                if(type == 1)
                    openresult = StaticClassReaderB.OpenComPort(port, ref fComAdr, fBaud, ref frmcomportindex);
                else
                    openresult = StaticClassReaderB.AutoOpenComPort(ref port, ref fComAdr, fBaud, ref frmcomportindex);
                if (openresult == 0)
                    return true;
                else
                {
                    System.Windows.Forms.MessageBox.Show("详细错误信息: " + GetReturnCodeDesc(openresult));
                    return false;
                }
            }
            catch { return false; }
        }


        public bool Connection(int com, int btl, string comName)
        {
            int port = 0;
            int openresult, i;
            openresult = 30;
            string temp;
            fComAdr = Convert.ToByte("FF", 16); // $FF;
            try
            {
                if (com == 0)//Auto
                {
                    fBaud = Convert.ToByte(btl);
                    if (fBaud > 2)
                        fBaud = Convert.ToByte(fBaud + 2);
                    openresult = StaticClassReaderB.AutoOpenComPort(ref port, ref fComAdr, fBaud, ref frmcomportindex);
                    fOpenComIndex = frmcomportindex;
                    if (openresult == 0 )
                    {
                        if ((fCmdRet == 0x35) | (fCmdRet == 0x30))
                        {
                            System.Windows.Forms.MessageBox.Show("串口通讯错误", "信息提示");
                            StaticClassReaderB.CloseSpecComPort(frmcomportindex);
                        }
                        return true;
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show(GetReturnCodeDesc(openresult));
                        return false;
                    }
                }
                else
                {
                    temp = comName; //ComboBox_COM.SelectedItem.ToString();
                    temp = temp.Trim();
                    port = Convert.ToInt32(temp.Substring(3, temp.Length - 3));
                    for (i = 6; i >= 0; i--)
                    {
                        fBaud = Convert.ToByte(i);
                        if (fBaud == 3)
                            continue;
                        openresult = StaticClassReaderB.OpenComPort(port, ref fComAdr, fBaud, ref frmcomportindex);
                        fOpenComIndex = frmcomportindex;
                        if (openresult == 0x35)
                        {
                            System.Windows.Forms.MessageBox.Show("串口已打开", "信息提示");
                            return false;
                        }
                        if (openresult == 0)
                        {

                            if ((fCmdRet == 0x35) || (fCmdRet == 0x30))
                            {
                                System.Windows.Forms.MessageBox.Show("串口通讯错误", "信息提示");
                                StaticClassReaderB.CloseSpecComPort(frmcomportindex);
                                return false;
                            }
                            return true;
                        }
                    }
                    System.Windows.Forms.MessageBox.Show(GetReturnCodeDesc(openresult));
                    return false;
                }
            }catch(Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return false;
            }
        }



        int closeresult = 0;

        public void EndClose()
        {
            StaticClassReaderB.CloseComPort();
        }

        public bool Close()
        {
            try
            {
                closeresult = StaticClassReaderB.CloseSpecComPort(fOpenComIndex);
                if (closeresult == 0)
                    return true;
                else
                    return false;
            }
            catch { return false; }
        }

        private int fCmdRet = 30;
        private string fInventory_EPC_List; //存贮询查列表（如果读取的数据没有变化，则不进行刷新）
        public string ReadEPC(out int cardNumb)
        {
            cardNumb = 0;
            byte[] EPC = new byte[5000];
            byte AdrTID = 0;
            byte LenTID = 0;
            byte TIDFlag = 0;
            int Totallen = 0;
            int CardNum = 0;
            string temps;
            fCmdRet = StaticClassReaderB.Inventory_G2(ref fComAdr, AdrTID, LenTID, TIDFlag, EPC, ref Totallen, ref CardNum, frmcomportindex);
            if ((fCmdRet == 1) | (fCmdRet == 2) | (fCmdRet == 3) | (fCmdRet == 4) | (fCmdRet == 0xFB))//代表已查找结束，
            {
                byte[] daw = new byte[Totallen];
                Array.Copy(EPC, daw, Totallen);
                temps = ByteArrayToHexString(daw);
                fInventory_EPC_List = temps;            //存贮记录

                System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Windows.Forms.Application.StartupPath + "\\read.ini", false, Encoding.GetEncoding("gbk"));
                sw.WriteLine(fInventory_EPC_List);
                sw.Close();

                return fInventory_EPC_List;
                ///label1.Text = fInventory_EPC_List;
                ///
               
            }
            else
                return "";
        }

        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            int mark = 1;
            foreach (byte b in data)
            {
                if (mark == 1)
                {
                    mark = 0;
                }
                else
                {
                    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
                }
            }
            return sb.ToString().ToUpper();

        }

        private void Form1_FormClosing(object sender) // FormClosingEventArgs e)
        {
            StaticClassReaderB.CloseComPort();
        }

        byte powerDbm;
        private void btn_szdbm_Click(object sender, EventArgs e)
        {
            //powerDbm = Convert.ToByte(ComboBox_PowerDbm.SelectedIndex);
            //fCmdRet = StaticClassReaderB.SetPowerDbm(ref fComAdr, powerDbm, frmcomportindex);
            //if (fCmdRet == 0)
            //    MessageBox.Show("设置功率成功");
            //else if (fCmdRet == 0xEE)
            //    MessageBox.Show("功率返回指令错误");
            //else
            //{
            //    MessageBox.Show("功率设置失败，原因：" + GetReturnCodeDesc(fCmdRet));
            //}
        }

        private string GetReturnCodeDesc(int cmdRet)
        {
            switch (cmdRet)
            {
                case 0x00:
                    return "操作成功";
                case 0x01:
                    return "询查时间结束前返回";
                case 0x02:
                    return "指定的询查时间溢出";
                case 0x03:
                    return "本条消息之后，还有消息";
                case 0x04:
                    return "读写模块存储空间已满";
                case 0x05:
                    return "访问密码错误";
                case 0x09:
                    return "销毁密码错误";
                case 0x0a:
                    return "销毁密码不能为全0";
                case 0x0b:
                    return "电子标签不支持该命令";
                case 0x0c:
                    return "对该命令，访问密码不能为全0";
                case 0x0d:
                    return "电子标签已经被设置了读保护，不能再次设置";
                case 0x0e:
                    return "电子标签没有被设置读保护，不需要解锁";
                case 0x10:
                    return "有字节空间被锁定，写入失败";
                case 0x11:
                    return "不能锁定";
                case 0x12:
                    return "已经锁定，不能再次锁定";
                case 0x13:
                    return "参数保存失败,但设置的值在读写模块断电前有效";
                case 0x14:
                    return "无法调整";
                case 0x15:
                    return "询查时间结束前返回";
                case 0x16:
                    return "指定的询查时间溢出";
                case 0x17:
                    return "本条消息之后，还有消息";
                case 0x18:
                    return "读写模块存储空间已满";
                case 0x19:
                    return "电子不支持该命令或者访问密码不能为0";
                case 0xFA:
                    return "有电子标签，但通信不畅，无法操作";
                case 0xFB:
                    return "无电子标签可操作";
                case 0xFC:
                    return "电子标签返回错误代码";
                case 0xFD:
                    return "命令长度错误";
                case 0xFE:
                    return "不合法的命令";
                case 0xFF:
                    return "参数错误";
                case 0x30:
                    return "通讯错误";
                case 0x31:
                    return "CRC校验错误";
                case 0x32:
                    return "返回数据长度有错误";
                case 0x33:
                    return "通讯繁忙，设备正在执行其他指令";
                case 0x34:
                    return "繁忙，指令正在执行";
                case 0x35:
                    return "端口已打开";
                case 0x36:
                    return "端口已关闭";
                case 0x37:
                    return "无效句柄";
                case 0x38:
                    return "无效端口";
                case 0xEE:
                    return "返回指令错误";
                default:
                    return "";
            }
        }

        //写入EPC
        private byte[] fPassWord = new byte[4];
        private int ferrorcode;
        public bool writeEPC(string epc)
        {
            ferrorcode = -1;
            byte WriteEPClen;
            byte ENum;
            WriteEPClen = Convert.ToByte(epc.Length / 2);
            ENum = Convert.ToByte(epc.Length / 4);
            byte[] EPC = new byte[ENum];
            EPC = HexStringToByteArray(epc);
            fPassWord = HexStringToByteArray("00000000");
            System.Threading.Thread.Sleep(1000);
            fCmdRet = StaticClassReaderB.WriteEPC_G2(ref fComAdr, fPassWord, EPC, WriteEPClen, ref ferrorcode, frmcomportindex);
            if (fCmdRet == 0)
                return true;
            else
                return false;
        }

        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }
    }
}
